package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.AllocateOrderDetailSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.AllocateOrderWithOrderDetailsSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.WmsSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.RequestUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.util.NameUtil;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.citrus.ots.common.util.TimeUtil;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderSDO;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf009Detail;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf009Request;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf009SDO;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapif009v2.dto.DoHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapif009v2.service.MnSapIf009V2Service;
import com.epoch.app.otsapplicationadaptersdk.service.ApiAdapterService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhoubc
 * @description: 平台请求sap调拨订单创建 ,调拔订单下发SAP接口（类型90）
 * @date 2021/9/28 21:09
 */
@Component
@Primary
public class MnSapIf009V2ServiceImpl implements MnSapIf009V2Service {
    private final Log log = Log.getLogger(MnSapIf009V2ServiceImpl.class);

    @Resource
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    private ApiAdapterService apiAdapterService;
    //原sap调拨单号
    public static final String ORIGIN_OUT_ORDER_CODE = "originOutOrderCode";
    /**
     * 原调拨单sap行号
     */
    public static final String ORIGIN_OUT_DETAIL_NO = "originOutDetailNo";

    @Override
    @ProcessInvoker(remark = "MnSapIf009V2Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object doHandler(DoHandlerRequest doHandlerRequest) {
        log.info("MnSapIf009ServiceImpl_doHandler_request:{}",JSON.toJSONString(doHandlerRequest));
        MnSapIf009Request request = new MnSapIf009Request();
        request.setMessageHeader(RequestUtils.generateMessageHeader("MnSapIf009","ECC"));
        MnSapIf009SDO sdo = new MnSapIf009SDO();
        AllocateOrderWithOrderDetailsSDO withOrderDetailsSDO = JSON.parseObject(doHandlerRequest.getMessage(),AllocateOrderWithOrderDetailsSDO.class);
        if (withOrderDetailsSDO == null)return null;
        if (withOrderDetailsSDO.getAllocateOrderSDO() == null)return null;
        AllocateOrderSDO allocateOrderSDO = withOrderDetailsSDO.getAllocateOrderSDO();
        sdo.setAllocateOrderId(allocateOrderSDO.getCode());
        sdo.setAllocateApplyOrderId(allocateOrderSDO.getAllocateApplyOrderCode());

        QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
        queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(allocateOrderSDO.getShipAreaId()));
        QueryCargoZoneByIdResponse shipAreaQuery = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
        WmsSDO shipWmsSDO = getWmsSDO(shipAreaQuery);


        queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(allocateOrderSDO.getReceiveAreaId()));
        QueryCargoZoneByIdResponse receiveAreaQuery = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
        WmsSDO receiveWmsSDO = getWmsSDO(receiveAreaQuery);
        if (Objects.equals(shipWmsSDO.getSapCompanyCode(),receiveWmsSDO.getSapCompanyCode())){
            sdo.setTypeCard("ZUB");
        }else {
            sdo.setTypeCard("ZTB");
        }

        sdo.setReceiveInventoryCode("DEFAULT".equals(receiveWmsSDO.getInventoryCode())?null:receiveWmsSDO.getInventoryCode());
        sdo.setReceiveFactoryCode(receiveWmsSDO.getFactoryCode());
        sdo.setDeliveryInventoryCode("DEFAULT".equals(shipWmsSDO.getInventoryCode())?null:shipWmsSDO.getInventoryCode());
        sdo.setDeliveryFactoryCode(shipWmsSDO.getFactoryCode());

        sdo.setShipType(allocateOrderSDO.getShipMethod()==null?null:"0" + allocateOrderSDO.getShipMethod() +"");
//        sdo.setCreateTime(TimeUtil.formatYYYYMMdd(allocateOrderSDO.getGmtCreate()));
        sdo.setCreateTime(TimeUtil.formatYYYY_MM_dd_time(allocateOrderSDO.getGmt_create()));
        sdo.setCreator(StringUtils.isNotBlank(allocateOrderSDO.getCreatorName()) ? allocateOrderSDO.getCreatorName() : NameUtil.getRealName(allocateOrderSDO.getCreator()));
        sdo.setRemark(allocateOrderSDO.getRemark());

//        SAPArea ship = new SAPArea();
//        ship.setCargoZoneIdList(Lists.newArrayList(withOrderDetailsSDO.getShipAreaId()));
//        QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = this.doHandler$callAPI2(ship);
//        Map shipMap = null;
//        WarehouseResponse shipArea = getWareHouse(shipMap);

//        SAPArea receive = new SAPArea();
//        receive.setCargoZoneIdList(Lists.newArrayList(withOrderDetailsSDO.getReceiveAreaId()));
//        queryCargoZoneByIdResponse = this.doHandler$callAPI2(receive);
//        Map receiveMap = null;
//        WarehouseResponse receiveArea = getWareHouse(receiveMap);
//        if (Objects.equals(shipArea.getSapCompanyCode(),receiveArea.getSapCompanyCode())){
//            sdo.setTypeCard("ZUB");
//        }else {
//            sdo.setTypeCard("ZTB");
//        }

        //TODO 需要对比 公司的编码 法人 是否相同
//        sdo.setReceiveFactoryCode(receiveArea.getSapFactoryCode());
//        sdo.setReceiveInventoryCode(receiveArea.getCode());
//        sdo.setDeliveryFactoryCode(shipArea.getSapFactoryCode());
//        sdo.setDeliveryInventoryCode(shipArea.getCode());

//        sdo.setShipType(withOrderDetailsSDO.getShipMethod() == null? null:String.valueOf(withOrderDetailsSDO.getShipMethod()));
//        sdo.setCreator(withOrderDetailsSDO.getCreator());
//        sdo.setCreateTime(TimeUtil.formatYYYYMMdd(withOrderDetailsSDO.getCreateTime()));
        sdo.setReturnGoods(Boolean.TRUE.equals(allocateOrderSDO.getReturnOrder())?"1":"0");
        sdo.setRemark(allocateOrderSDO.getRemark());
        sdo.setFeatures(allocateOrderSDO.getFeatures());
        if (Boolean.TRUE.equals(allocateOrderSDO.getReturnOrder())){
            Map<String, String> mainBizFeatures = FeatureUtil.fromString(allocateOrderSDO.getBizFeatures());
            sdo.setExt(mainBizFeatures.get(ORIGIN_OUT_ORDER_CODE));
        }
        List<MnSapIf009Detail> details = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(withOrderDetailsSDO.getAllocateOrderDetailSDOS())){
            for (AllocateOrderDetailSDO detailSDO : withOrderDetailsSDO.getAllocateOrderDetailSDOS()){
                MnSapIf009Detail detail = new MnSapIf009Detail();
                detail.setAllocateOrderLineId(detailSDO.getLineNo());
                detail.setScItemId(SapAndCrmFieldDealUtils.generateIdField(detailSDO.getScItemCode()));
                detail.setQuantity(detailSDO.getQuantity());
                detail.setUnit(detailSDO.getUnit());

                detail.setExpectedDeliveryDate(TimeUtil.formatYYYY_MM_dd(allocateOrderSDO.getExpectedDeliveryDate()));
                detail.setProduceDate(TimeUtil.formatYYYY_MM_dd(detailSDO.getExpectedProduceDate()));
                detail.setRemark(detailSDO.getRemarks());
                detail.setFeatures(detailSDO.getFeatures());
                //退单时
                if (Boolean.TRUE.equals(allocateOrderSDO.getReturnOrder())){
                    Map<String, String> detailBizFeatures = FeatureUtil.fromString(detailSDO.getBizFeatures());
                    detail.setExt(detailBizFeatures.get(ORIGIN_OUT_DETAIL_NO));
                }
                details.add(detail);
            }
        }
        sdo.setItems(details);
        request.setData(Lists.newArrayList(sdo));
        log.info("MnSapIf009ServiceImpl reqSapAllocateOrderCreate req:{}",JSON.toJSONString(request));
        return apiAdapterService.reqSapAllocateOrderCreate(request);
    }

    public static WmsSDO getWmsSDO(QueryCargoZoneByIdResponse response){
        WmsSDO wmsSDO = new WmsSDO();
        if (response !=null && CollectionUtils.isNotEmpty(response.getResult())){
            JSONArray array = JSON.parseArray(JSON.toJSONString(response.getResult()));
            if (array != null && array.size() > 0){
                JSONObject data = array.getJSONObject(0);
                if (data != null){
//                wmsSDO.setInventoryCode(data.getString("code"));
                    wmsSDO.setInventoryCode(data.getString("warehouseCode"));
                    wmsSDO.setFactoryCode(data.getString("sapFactoryCode"));
                    wmsSDO.setSapCompanyCode(data.getString("sapCompanyCode"));
                }
//                if (StringUtils.isNotBlank(data.getString("features"))){
//                    JSONObject features = JSON.parseObject(data.getString("features"));
//                    if (features != null){
//                        wmsSDO.setSapCompanyCode(features.getString(""));
//                    }
//                }
            }
        }
        return wmsSDO;
    }


}
